import { useRef, useEffect, useState, useCallback } from "react";
import { useParams } from "react-router-dom";
import { useChatStore } from "../stores/useChatStore";
import { useAgentStore } from "../stores/useAgentStore";
import { useProviderStore } from "../stores/useProviderStore";
import { MessageList } from "../components/MessageList";
import { EnhancedChatInput } from "../components/EnhancedChatInput";
import { useHotkeys } from "../hooks/useHotkeys";
import { useStreaming } from "../hooks/useStreaming";
import apiService from "../lib/api";
import { toast } from "../hooks/use-toast";

// 聊天消息类型
interface ChatMessage {
  id: string;
  role: "user" | "assistant";
  content: string;
  timestamp: Date;
  status?: "sending" | "sent" | "delivered" | "error";
  reactions?: string[];
  isStreaming?: boolean;
}

export default function ChatPage() {
  const { id: sessionId } = useParams();
  const {
    inputText,
    chatMessages,
    currentSessionId,
    setInputText,
    setLoading,
    setChatMessages,
    addChatMessage,
    updateChatMessage,
    setCurrentSessionId,
    loadChatMessages,
  } = useChatStore();

  const { selectedAgent } = useAgentStore();
  const { isProviderFullyConfigured } = useProviderStore();

  // 本地状态
  const [editingMessageId, setEditingMessageId] = useState<string | null>(null);
  const [editedText, setEditedText] = useState("");
  const [isTyping, setIsTyping] = useState(false);
  const [streamingMessage, setStreamingMessage] = useState<ChatMessage | null>(
    null,
  );
  const [copiedMessageId, setCopiedMessageId] = useState<string | null>(null);
  const [attachedFiles, setAttachedFiles] = useState<File[]>([]);

  // Refs
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLTextAreaElement | null>(null);

  // 流式响应处理
  const { startStreaming, stopStreaming, isStreaming } = useStreaming({
    onChunk: (chunk) => {
      if (streamingMessage) {
        setStreamingMessage((prev) => ({
          ...prev!,
          content: prev!.content + chunk,
          isStreaming: true,
        }));
      }
    },
    onComplete: (content: string) => {
      if (streamingMessage) {
        const finalMessage: ChatMessage = {
          ...streamingMessage,
          content: content,
          isStreaming: false,
          status: "sent",
        };
        addChatMessage(finalMessage);
        setStreamingMessage(null);
      }
      setLoading(false);
      setIsTyping(false);
    },
    onError: (error) => {
      console.error("Streaming error:", error);
      const errorMessage: ChatMessage = {
        id: Date.now().toString(),
        role: "assistant",
        content: "抱歉，发送消息时出现错误。请稍后重试。",
        timestamp: new Date(),
        status: "error",
      };
      addChatMessage(errorMessage);
      setStreamingMessage(null);
      setLoading(false);
      setIsTyping(false);
    },
  });

  // 键盘快捷键
  useHotkeys([
    { key: "ctrl+k", callback: () => inputRef.current?.focus() },
    { key: "ctrl+l", callback: () => setChatMessages([]) },
    {
      key: "esc",
      callback: () => {
        setEditingMessageId(null);
        setEditedText("");
      },
    },
  ]);

  // 自动滚动到底部
  const scrollToBottom = useCallback(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, []);

  useEffect(() => {
    scrollToBottom();
  }, [chatMessages, streamingMessage, scrollToBottom]);

  // 加载会话消息
  useEffect(() => {
    if (sessionId && sessionId !== currentSessionId) {
      setCurrentSessionId(sessionId);
      loadChatMessages(sessionId);
    }
  }, [sessionId, currentSessionId, setCurrentSessionId, loadChatMessages]);

  // 消息操作
  const handleSendMessage = async (message: string) => {
    if (!message.trim()) return;

    // 确保选中的代理及其提供商已配置
    if (!selectedAgent || !isProviderFullyConfigured(selectedAgent.provider)) {
      toast({
        title: "配置错误",
        description: "请先在设置中配置所选代理的提供商。",
        variant: "destructive",
      });
      return;
    }

    setLoading(true);
    setIsTyping(true);

    // 添加用户消息
    const userMessage: ChatMessage = {
      id: Date.now().toString(),
      role: "user",
      content: message,
      timestamp: new Date(),
      status: "sent",
    };
    addChatMessage(userMessage);

    // 创建流式消息占位符
    const assistantMessage: ChatMessage = {
      id: (Date.now() + 1).toString(),
      role: "assistant",
      content: "",
      timestamp: new Date(),
      isStreaming: true,
    };
    setStreamingMessage(assistantMessage);

    // 清空输入
    setInputText("");

    try {
      if (selectedAgent?.name) {
        await startStreaming({
          agent_id: selectedAgent?.id,
          prompt: message,
          history: chatMessages.slice(-10),
        });
      } else {
        const response = await apiService.chat(
          selectedAgent?.name || "default",
          {
            prompt: message,
            history: chatMessages.slice(-10),
          },
        );

        if (streamingMessage) {
          const finalMessage: ChatMessage = {
            ...streamingMessage,
            content: response.content || response.message,
            isStreaming: false,
            status: "sent",
          };
          addChatMessage(finalMessage);
          setStreamingMessage(null);
        }
        setLoading(false);
        setIsTyping(false);
      }
    } catch (error) {
      console.error("Failed to send chat message:", error);
      stopStreaming();

      const errorMessage: ChatMessage = {
        id: Date.now().toString(),
        role: "assistant",
        content: "抱歉，发送消息时出现错误。请稍后重试。",
        timestamp: new Date(),
        status: "error",
      };
      addChatMessage(errorMessage);
      setStreamingMessage(null);
      setLoading(false);
      setIsTyping(false);
    }
  };

  const handleCopyMessage = async (text: string, messageId: string) => {
    try {
      await navigator.clipboard.writeText(text);
      setCopiedMessageId(messageId);
      setTimeout(() => setCopiedMessageId(null), 2000);
    } catch (error) {
      console.error("Failed to copy message:", error);
    }
  };

  const handleEditMessage = (messageId: string) => {
    const message = chatMessages.find((m) => m.id === messageId);
    if (message) {
      setEditingMessageId(messageId);
      setEditedText(message.content);
    }
  };

  const handleSaveEditedMessage = (messageId: string) => {
    updateChatMessage(messageId, { content: editedText });
    setEditingMessageId(null);
    setEditedText("");
  };

  const handleRegenerateMessage = async (messageId: string) => {
    const message = chatMessages.find((m) => m.id === messageId);
    if (message?.role === "assistant") {
      const userMessageIndex =
        chatMessages.findIndex((m) => m.id === messageId) - 1;
      const userMessage = chatMessages[userMessageIndex];

      if (userMessage) {
        const updatedMessages = chatMessages.filter((m) => m.id !== messageId);
        setChatMessages(updatedMessages);
        await handleSendMessage(userMessage.content);
      }
    }
  };

  const handleAddReaction = (messageId: string, reaction: string) => {
    updateChatMessage(messageId, {
      reactions: [
        ...(chatMessages.find((m) => m.id === messageId)?.reactions || []),
        reaction,
      ],
    });
  };

  // 计算所有消息（包括流式消息）
  const allMessages = streamingMessage
    ? [...chatMessages, streamingMessage]
    : chatMessages;

  return (
    <div className="flex flex-col h-full">
      {/* 消息列表 */}
      <div className="flex-1 overflow-hidden relative">
        <MessageList
          messages={allMessages.map((msg) => ({
            id: msg.id,
            text: msg.content,
            sender: msg.role,
            timestamp: msg.timestamp,
            status: msg.status,
            reactions: msg.reactions,
            isStreaming: msg.isStreaming,
          }))}
          editingMessageId={editingMessageId}
          editedText={editedText}
          onCopyMessage={(text, messageId) =>
            handleCopyMessage(text, messageId)
          }
          onEditMessage={handleEditMessage}
          onSaveEditedMessage={handleSaveEditedMessage}
          onCancelEdit={() => {
            setEditingMessageId(null);
            setEditedText("");
          }}
          onAddReaction={handleAddReaction}
          onEditChange={setEditedText}
          onRegenerateMessage={handleRegenerateMessage}
          currentAgentName={selectedAgent?.name}
          currentAgentDescription={selectedAgent?.description}
          copiedMessageId={copiedMessageId}
        />

        {/* 滚动锚点 */}
        <div ref={messagesEndRef} />
      </div>

      {/* 输入区域 */}
      <div className="border-t border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900">
        <EnhancedChatInput
          inputText={inputText}
          isTyping={isTyping || isStreaming}
          onInputChange={setInputText}
          onSubmit={(e) => {
            e.preventDefault();
            handleSendMessage(inputText);
          }}
          inputRef={inputRef as React.RefObject<HTMLTextAreaElement>}
          onStopGeneration={stopStreaming}
          onFileAttach={(files) => {
            setAttachedFiles((prev) => [...prev, ...files]);
          }}
          onVoiceRecord={(isRecording) => {
            console.log("Voice recording:", isRecording);
          }}
          attachedFiles={attachedFiles}
          onRemoveFile={(index) => {
            setAttachedFiles((prev) => prev.filter((_, i) => i !== index));
          }}
          placeholder="输入消息... 支持拖拽文件、语音输入和表情符号"
        />
      </div>
    </div>
  );
}

